package com.yunzai.login.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

public class CaptchaGenerator {
    // 图片宽度和高度
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;

    public static String getBase64(String code) throws IOException {

        // 创建图片对象
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制验证码字符
        drawRandomText(g, code);

        // 添加干扰线
        drawInterferenceLines(g);

        // 释放图形资源
        g.dispose();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();

        // 将验证码转为Base64
        return "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
    }


    /**
     * 绘制随机文本
     */
    private static void drawRandomText(Graphics2D g, String code) {
        Random random = new Random();
        g.setFont(new Font("Arial", Font.BOLD, 28));

        for (int i = 0; i < code.length(); i++) {
            // 设置随机颜色
            g.setColor(new Color(
                    random.nextInt(150) + 50,  // R (50-200)
                    random.nextInt(150) + 50,  // G (50-200)
                    random.nextInt(150) + 50   // B (50-200)
            ));

            // 计算字符位置（加入随机偏移）
            int x = 20 * i + 10 + random.nextInt(8);
            int y = 25 + random.nextInt(8);

            // 绘制字符
            g.drawString(String.valueOf(code.charAt(i)), x, y);
        }
    }

    /**
     * 绘制干扰线
     */
    private static void drawInterferenceLines(Graphics2D g) {
        Random random = new Random();
        g.setStroke(new BasicStroke(1.5f));

        // 绘制3条随机颜色的干扰线
        for (int i = 0; i < 3; i++) {
            g.setColor(new Color(
                    random.nextInt(200),
                    random.nextInt(200),
                    random.nextInt(200)
            ));

            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);

            g.drawLine(x1, y1, x2, y2);
        }
    }
}